//
//  ComposeViewController.swift
//  HMWeibo08
//
//  Created by 唐万超 on 15/8/7.
//  Copyright © 2015年 唐万超. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController {

    override func loadView() {
        
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        
        prepareNav()
        prepareToolBar()
        prepareTextView()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 进入页面打开键盘
        textView.becomeFirstResponder()
    }
    
    /// 关闭发送微博页面
    func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
        textView.resignFirstResponder()
    
    }
    
    // MARK: - 键盘监听方法
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addKeyboardObserver()
    }
    
    // 视图控制器销毁的时候删除通知
    deinit {
        removeKeyboardObserver()
    }

    /// 添加键盘监听通知
    private func addKeyboardObserver() {
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    /// toolBar的底部约束
    var toolbarBottomCon: NSLayoutConstraint?
    // 键盘监听方法
    func keyboardChanged(n: NSNotification)
    {
        print(n)
        // 取得键盘的弹出结束frame
        let rect = n.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue
        
        // 取得动画时间
        let duration = n.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]!.doubleValue
        // 更改约束
        toolbarBottomCon?.constant = -(UIScreen.mainScreen().bounds.height - rect.origin.y)
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    /// 删除键盘监听通知
    private func removeKeyboardObserver() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /// 发送微博
    func sendStatus() {
        print("发送微博。。")
    }
    
    /// 表情按钮点击
    func inputEmoticon() {
        print("表情按钮")
    }
    
    /// 准备textView
    private func prepareTextView() {
    
        view.addSubview(textView)
        
        textView.backgroundColor = UIColor.whiteColor()
        
        // 设置约束
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolbar, size: nil)
        
        textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        
        // 添加占位图片
        textView.addSubview(placeholderLabel)
        placeholderLabel.text = "分享新鲜事..."
        placeholderLabel.sizeToFit()
        
        placeholderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
        
        
    }

    /// 准备toolBar
    private func prepareToolBar() {
        
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        view.addSubview(toolbar)
        
       let cons = toolbar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        
        toolbarBottomCon = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        // 定义一个数组
        let itemSettings = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        for dict in itemSettings {
            
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["action"]))
        
            // 追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
           
        }
        // 移除最后的弹簧
        items.removeLast()
        
        // 设置toolBar
        toolbar.items = items
    }
    
    /// 准备导航栏
    private func prepareNav() {
        // 左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        // 中间标题栏
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 32))
        
        // 标题文字
        let titleLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15)
        titleLabel.text = "发送微博"
        titleLabel.sizeToFit()
        titleView.addSubview(titleLabel)
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        
        // 用户名文字
        let nameLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 13)
        nameLabel.text  = UserAccount.loadAccount()?.name
        nameLabel.sizeToFit()
        titleView.addSubview(nameLabel)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
        
        
    }
    
    
    // MARK: 懒加载控件
    
    /// 工具栏
    private lazy var toolbar = UIToolbar()
    
    /// 文本视图
    private lazy var textView: UITextView = {
    
        let tv = UITextView()
        // 设置垂直滚动
        tv.alwaysBounceVertical = true
        tv.font = UIFont.systemFontOfSize(18)
        
        // 设置滚动退出键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return tv
        
    }()
    
    /// 占位标签
    private lazy var placeholderLabel: UILabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)
    
}
